package com.hyt.it.ogt.ks.service.impl;

import java.util.Objects;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.it.ogt.ks.config.KsBizRunTimeException;
import com.hyt.it.ogt.ks.enums.BizStatusCode;
import com.hyt.it.ogt.ks.feign.KwClient;
import com.hyt.it.ogt.ks.feign.model.ExamDTO;
import com.hyt.it.ogt.ks.service.ExamInfoCacheService;
import com.hyt.it.ogt.ks.util.EnCacheUtil;
import com.hyt.it.ogt.ks.util.KeyDefineCommon;

import lombok.extern.slf4j.Slf4j;

/**
 * @author wuyingge
 * @version 1.0.0
 * @ClassName ExamInfoCacheServiceImpl.java
 * @Description 考试配置信息缓存
 * @createTime 2022年04月12日 17:22:00
 */
@Slf4j
@Service
public class ExamInfoCacheServiceImpl implements ExamInfoCacheService {
    @Resource
    private EnCacheUtil enCacheUtil;
    @Resource
    private KwClient kwClient;

    /**
     * 从缓存中获取考试配置信息
     * @param examId
     * @return
     */
    @Override
    public ExamDTO getExamInfoFromCache(String examId){
    	
        String key = KeyDefineCommon.getExamInfoCacheInfoKey(examId);
        
        String examInfoFromCache = enCacheUtil.getExamInfoFromCache(key);
        
        if(StringUtils.isNotBlank(examInfoFromCache)){
            ExamDTO examDTO = JSON.parseObject(examInfoFromCache, ExamDTO.class);
            return examDTO;
        }
        //没有在缓存当中
        String repRtn = kwClient.getExamInfo(examId);
        ApiResponse<ExamDTO> res = ApiResponse.ConvertRet(repRtn, ExamDTO.class);
        if (res.getCode().intValue() != BizStatusCode.KW_SUCCESS_OK.getCode().intValue()) {
            throw new KsBizRunTimeException(BizStatusCode.GET_EXAM_INFO_FAIL.getCode());
        }
        ExamDTO examDTO = JSON.parseObject(JSON.toJSONString(res.getData()), ExamDTO.class);
        //放入组成
        if(Objects.nonNull(examDTO)){
            enCacheUtil.putExamInfoToCache(key,JSON.toJSONString(examDTO),null);
        }
        return examDTO;
    }
}
